// FiveDice Application. Chris Born, 2007

#import "FiveDiceController.h"
#include <libc.h>
#include <math.h>

@implementation FiveDiceController

#pragma mark Init and Dealloc

- (id)init {
	if(self = [super init])
	{
	}
	return self;
}

- (void)dealloc {
	[super dealloc];
}

#pragma mark UIApplication delegates

- (void)applicationDidFinishLaunching:(id)unused {
	NSLog(@"Application Finished Launching");
	srandom(time(0));

	_diceImages = [[[NSArray alloc] initWithArray:[self diceImages]] autorelease];
	[self setupInterface];
}

- (void) applicationWillSuspend
{
	// TODO: Persistence of game state
}

#pragma mark Button delegates

- (void)navigationBar:(UINavigationBar*)bar buttonClicked:(int)button
{
	if (button == 1) {
		NSLog(@"%s Clicked Menu", _cmd);
	} else if (button == 0) {
		NSLog(@"%s Clicked Roll", _cmd);
		[self rollDice];
	}
}

#pragma mark Interface

- (void)setupInterface {
	_colorSpace = CGColorSpaceCreateDeviceRGB();
	
	_contentRect = [UIHardware fullScreenApplicationContentRect];
	_contentRect.origin.x = 0.0f;
	_contentRect.origin.y = 0.0f;
	
	UIWindow *window = [[UIWindow alloc] initWithContentRect:[UIHardware fullScreenApplicationContentRect]];
	
	_mainView = [[UIView alloc] initWithFrame:_contentRect];

	UIImageView *background = [[[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, _contentRect.size.width, _contentRect.size.height)] autorelease];
	_bundle = [NSBundle mainBundle];
  	NSString 	*imgPath = [_bundle pathForResource:@"greenfelt" ofType:@"png"];
  	UIImage		*backgroundImg = [[UIImage alloc]initWithContentsOfFile:imgPath];
	[background setImage:backgroundImg];	
	[_mainView addSubview:background];
	
 	[self setupScoreCardView];
	
	[self setupNavbar];
		
	[self setupBottomBar];
	[self draw5Dice];
	
	[window setContentView:_mainView];
	[self setMainWindow:window];

	[window orderFront:self];
	[window makeKey:self];
	[window _setHidden:NO];
}

- (void)setupNavbar {
	navBar = [[UINavigationBar alloc] init];
	[navBar setFrame:CGRectMake(_contentRect.origin.x, _contentRect.origin.y, _contentRect.size.width, 45.0f)];
	[navBar setBarStyle:1];

	UIImageView *navBarBackground = [[[UIImageView alloc] initWithFrame:CGRectMake(_contentRect.origin.x, _contentRect.origin.y, _contentRect.size.width, 45.0f)] autorelease];
  	NSString	*path = [_bundle pathForResource:@"navbar" ofType:@"png"];
  	UIImage		*navBarImg = [[UIImage alloc]initWithContentsOfFile:path];

	[navBarBackground setImage:navBarImg];	
	[navBar addSubview:navBarBackground];
	[navBar showLeftButton:@"Menu" withStyle:2 rightButton:@"Roll" withStyle:1];

	[navBar setDelegate:self];
	[navBar enableAnimation];
	
	[_mainView addSubview:navBar];
}

- (void)setupBottomBar {
	UIImageView	*bottomBar = [[[UIImageView alloc] initWithFrame:CGRectMake(_contentRect.origin.x, _contentRect.size.height - 32, _contentRect.size.width, 35.0f)] autorelease];
	NSString	*path = [_bundle pathForResource:@"bottombar" ofType:@"png"];
  	UIImage		*bottomBarImg = [[UIImage alloc]initWithContentsOfFile:path];
	[bottomBar setImage:bottomBarImg];
	
	[_mainView addSubview:bottomBar];
}

- (int)randomDie {
		int i = (random() % (5-0+1)) + 0;
		return i;
}

- (void)draw5Dice {
	_diceButtons = [[NSMutableArray alloc] init];
	[_diceButtons retain];
	int i = 0;
	for(i = 0; i < 5; ++i)
	{
		[_diceButtons addObject:[self diceButtonWithValue:0 position:i]];
		[_mainView addSubview:[_diceButtons objectAtIndex:i]];
	}
}

- (void)updateDice {
	_diceValues = [[NSMutableArray alloc] init];
	[_diceValues retain];	
		
	int i = 0;
	for(i = 0; i < 5; ++i)
	{
		int r = [self randomDie];
		[_diceValues addObject:[NSNumber numberWithInt:r+1]];
		[[_diceButtons objectAtIndex:i] setImage:[self dieImageWithValue:r downImage:NO] forState:0];
		[[_diceButtons objectAtIndex:i] setImage:[self dieImageWithValue:r downImage:YES] forState:1];
	}
}

- (void)rollDice {	
	_animTimer = [NSTimer scheduledTimerWithTimeInterval:0.05
											  	  target:self
												selector:@selector(animateButtonImages:)
												userInfo:nil
											 	 repeats:YES];
}

- (void)animateButtonImages:(NSTimer *)aTimer {
	if (_animCount >= 10) {
		[_animTimer invalidate];
		_animCount = 0;
		
		int i = 0;
		for(i = 0; i < [_diceValues count]; ++i)
		{
			NSLog(@"Value: %i", [[_diceValues objectAtIndex:i] intValue]);
		}
		NSLog(@"%s Done animating button images.", _cmd);
	} else {
		[self updateDice];
		_animCount = _animCount + 1;
	}
}

- (UIPushButton *)diceButtonWithValue:(int)val position:(int)pos {
	
	UIPushButton	*button = [[[UIPushButton alloc] initWithFrame:[self rectForDiePosition:pos]] autorelease];
	[button setImage:[self dieImageWithValue:val downImage:NO] forState:0];
	[button setImage:[self dieImageWithValue:val downImage:YES] forState:1];
	[button addTarget:self action:@selector(dieSelected:) forEvents: (255)];

	return button;
}

- (void)dieSelected:(UINavBarButton *)button {
	if (![button isPressed]) {
		if (button == [_diceButtons objectAtIndex:0]) [[_diceButtons objectAtIndex:0] setHighlighted:YES];
		if (button == [_diceButtons objectAtIndex:1]) NSLog(@"Button held: %i", 1);
		if (button == [_diceButtons objectAtIndex:2]) NSLog(@"Button held: %i", 2);
		if (button == [_diceButtons objectAtIndex:3]) NSLog(@"Button held: %i", 3);
		if (button == [_diceButtons objectAtIndex:4]) NSLog(@"Button held: %i", 4);
    }
}

- (struct CGRect)rectForDiePosition:(int)pos {
	struct CGRect	diePosition;
	switch (pos) {
		case 0:
		diePosition = CGRectMake(_contentRect.origin.x, _contentRect.origin.x + 52, 64, 71);
		break;
		case 1:
		diePosition = CGRectMake(_contentRect.origin.x + 64, _contentRect.origin.x + 52, 64, 71);
		break;
		case 2:
		diePosition = CGRectMake(_contentRect.origin.x + 128, _contentRect.origin.x + 52, 64, 71);
		break;
		case 3:
		diePosition = CGRectMake(_contentRect.origin.x + 192, _contentRect.origin.x + 52, 64, 71);
		break;
		case 4:
		diePosition = CGRectMake(_contentRect.origin.x + 256, _contentRect.origin.x + 52, 64, 71);
		break;
	}
	return diePosition;
}

- (NSMutableArray *)diceImages {
	NSMutableArray	*array = [[NSMutableArray alloc] init];
	int i = 0;
	for (i = 0; i < 5; i++) {
		NSLog(@"%s i is %i", _cmd, i);
		
	}
	return array;
}

- (UIImage *)dieImageWithValue:(int)val downImage:(BOOL)down {

	NSString		*name;
	NSString		*path;
	
	switch (val) {
		case 0:
		name = @"one";
		break;
		case 1:
		name = @"two";
		break;
		case 2:
		name = @"three";
		break;
		case 3:
		name = @"four";
		break;
		case 4:
		name = @"five";
		break;
		case 5:
		name = @"six";
		break;
	}
	
	if (down) {
		path = [_bundle pathForResource:[NSString stringWithFormat:@"%@_d",name] ofType:@"png"];
	} else {
		path = [_bundle pathForResource:name ofType:@"png"];
	}
	
	UIImage		*image = [[UIImage alloc]initWithContentsOfFile:path];
	[image retain];
	return image;
}

#pragma mark Score Card View

- (void)setupScoreCardView {
	struct CGRect rect = CGRectMake(_contentRect.origin.x + 4, _contentRect.origin.y + 147, _contentRect.size.width - 8, _contentRect.size.height - 33);	
	_scoreCardView = [[UIView alloc] initWithFrame:rect];
	
	UIImageView *background = [[[UIImageView alloc] initWithFrame:CGRectMake(0,0,314,261)] autorelease];
	_bundle = [NSBundle mainBundle];
  	NSString 	*imgPath = [_bundle pathForResource:@"scorecard" ofType:@"png"];
  	UIImage		*backgroundImg = [[UIImage alloc]initWithContentsOfFile:imgPath];
	[background setImage:backgroundImg];	
	
	[_scoreCardView addSubview:background];
	
	//struct __GSFont *font = [NSClassFromString(@"WebFontCache") createFontWithFamily:@"Helvetica" traits:2 size:10];
	
	UITextLabel	*cardLabel = [[UITextLabel alloc] initWithFrame:CGRectMake(22, 8, 270, 35)];
//	WebFontCache	*fontCache = [[WebFontCache alloc]init];
	
//	[cardLabel setFont:[fontCache createFontWithFamily:@"Georgia" traits:2 size:16]];
	[cardLabel setText:@"Score Card"];
	[cardLabel setCentersHorizontally:YES];
	[cardLabel setShadowOffset:CGSizeMake(0,1)];
	
	float _clearColor[4] = {1, 1, 1, 0};
	[cardLabel setBackgroundColor: CGColorCreate( _colorSpace, _clearColor)];
	[_scoreCardView addSubview:cardLabel];
	
	UIView	*line = [[UIView alloc] initWithFrame:CGRectMake(22,44,270,1)];

	float _blackColor[4] = {0, 0, 0, 1};
	[line setBackgroundColor: CGColorCreate( _colorSpace, _blackColor)];
	[_scoreCardView addSubview:line];
	
	[self createScoreCardTable];
	
	[_mainView addSubview: _scoreCardView];
}

- (void)createScoreCardTable {
	
		UITableColumn *col = [[UITableColumn alloc]
			initWithTitle:@"Scores"
			identifier:@"scores"
			width:285];
				 
		NSLog(@"Score Card >> init table...");
		_scoreCardTable = [[UITable alloc] initWithFrame:CGRectMake(22, 45, 270, 236)];
		[_scoreCardTable addTableColumn: col];
		[_scoreCardTable setSeparatorStyle: 1];
		[_scoreCardTable setDelegate: self];
		[_scoreCardTable setDataSource: self];
		[_scoreCardTable setRowHeight:34.0];

		float _clearColor[4] = {1, 1, 1, 0};
		[_scoreCardTable setBackgroundColor: CGColorCreate( _colorSpace, _clearColor)];

		_scoreCardCells = [[NSMutableArray alloc] init];
		[self scoreCardCells];
		
		[self reloadData];
				
		[_scoreCardView addSubview: _scoreCardTable];
}

- (void)scoreCardCells {
	[_scoreCardCells removeAllObjects];
	[_scoreCardCells addObject:@"Aces:"];
	[_scoreCardCells addObject:@"Twos:"];
	[_scoreCardCells addObject:@"Threes:"];
	[_scoreCardCells addObject:@"Fours:"];
	[_scoreCardCells addObject:@"Fives:"];
	[_scoreCardCells addObject:@"Sixes:"];
	[_scoreCardCells addObject:@"3 of a kind:"];
	[_scoreCardCells addObject:@"4 of a kind:"];
	[_scoreCardCells addObject:@"Full House:"];
	[_scoreCardCells addObject:@"Sm Straight:"];
	[_scoreCardCells addObject:@"Lg Straight:"];
	[_scoreCardCells addObject:@"YAHTZEE:"];
	[_scoreCardCells addObject:@"Chance:"];	
}

- (int) numberOfRowsInTable: (UITable *)table
{
    return [_scoreCardCells count];	
}

- (UITableCell *)table:(UITable *)table cellForRow:(int)row column:(UITableColumn *)col
{
	UIImageAndTextTableCell *cell = [[UIImageAndTextTableCell alloc] init];
	[cell setTitle:[_scoreCardCells objectAtIndex:row]];
	
	switch (row) {
		case 0:
		[cell setImage:[UIImage applicationImageNamed:@"ones.png"]];
		break;
		case 1:
		[cell setImage:[UIImage applicationImageNamed:@"twos.png"]];
		break;
		case 2:
		[cell setImage:[UIImage applicationImageNamed:@"threes.png"]];
		break;
		case 3:
		[cell setImage:[UIImage applicationImageNamed:@"fours.png"]];
		break;
		case 4:
		[cell setImage:[UIImage applicationImageNamed:@"fives.png"]];
		break;
		case 5:
		[cell setImage:[UIImage applicationImageNamed:@"sixes.png"]];
		break;
		case 6:
		[cell setImage:[UIImage applicationImageNamed:@"3ofakind.png"]];
		break;
		case 7:
		[cell setImage:[UIImage applicationImageNamed:@"4ofakind.png"]];
		break;
		case 8:
		[cell setImage:[UIImage applicationImageNamed:@"fullhouse.png"]];
		break;
		case 9:
		[cell setImage:[UIImage applicationImageNamed:@"smstraight.png"]];
		break;
		case 10:
		[cell setImage:[UIImage applicationImageNamed:@"lgstraight.png"]];
		break;
		case 11:
		[cell setImage:[UIImage applicationImageNamed:@"yahtzee.png"]];
		break;
	}	
	return cell;
}

-(void)reloadData
{
	[_scoreCardTable reloadData];
}

/*
- (void)setupScoreCardTable {
	[self setupTableCells];
	_scoreCardTable = [[UIPreferencesTable alloc] initWithFrame:CGRectMake(10, 10, 294, 251)];	
	[_scoreCardTable setDataSource:self];
	[_scoreCardTable setDelegate:self];
	
	float backParts[4] = {1, 1, 1, 0};
	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
	[_scoreCardTable setBackgroundColor: CGColorCreate( colorSpace, backParts)];
	
	[_scoreCardView addSubview:_scoreCardTable];
}

- (void)setupTableCells {
	acesCell = [[UIPreferencesTextTableCell alloc] initWithFrame:CGRectMake(0, 0, 294, 48)];
	[acesCell setValue:@"0"];
	[acesCell setTitle:@"Aces (Total 1's)"];
	
	twosCell = [[UIPreferencesTextTableCell alloc] initWithFrame:CGRectMake(0, 0, 294, 48)];
	[twosCell setValue:@"0"];
	[twosCell setTitle:@"Twos (Total 2's)"];
	
	threesCell = [[UIPreferencesTextTableCell alloc] initWithFrame:CGRectMake(0, 0, 294, 48)];
	[threesCell setValue:@"0"];
	[threesCell setTitle:@"Threes (Total 3's)"];
	
	foursCell = [[UIPreferencesTextTableCell alloc] initWithFrame:CGRectMake(0, 0, 294, 48)];
	[foursCell setValue:@"0"];
	[foursCell setTitle:@"Fours (Total 4's)"];
	
	fivesCell = [[UIPreferencesTextTableCell alloc] initWithFrame:CGRectMake(0, 0, 294, 48)];
	[fivesCell setValue:@"0"];
	[fivesCell setTitle:@"Fives (Total 5's)"];

	sixesCell = [[UIPreferencesTextTableCell alloc] initWithFrame:CGRectMake(0, 0, 294, 48)];
	[sixesCell setValue:@"0"];
	[sixesCell setTitle:@"Sixes (Total 6's)"];
}

- (int)numberOfGroupsInPreferencesTable:(id)preferencesTable
{
	return 1;
}

- (int)preferencesTable:(id)preferencesTable numberOfRowsInGroup:(int)group
{
	int rowCount = 0;
	switch (group){
		case 0:
		rowCount = 6;
		break;
	}
	return rowCount;
}

- (id)preferencesTable:(id)preferencesTable cellForRow:(int)row inGroup:(int)group
{
	NSLog(@"PreferencesController: cellForRow:");
	id prefCell = nil;
	switch (group) {
		case 0:
		switch (row) {
			case 0:
			prefCell = acesCell;
			break;
			case 1:
			prefCell = twosCell;
			break;
			case 2:
			prefCell = threesCell;
			break;
			case 3:
			prefCell = foursCell;
			break;
			case 4:
			prefCell = fivesCell;
			break;
			case 5:
			prefCell = sixesCell;
			break;

		}
		break;
	}
	return prefCell;
}

- (id)preferencesTable:(id)preferencesTable titleForGroup:(int)group
{
	NSString *title = nil;
	switch (group)
	{
	case 0:
		title = @"Upper Section";
		break;
	}
	return title;
}

- (float)preferencesTable:(id)preferencesTable heightForRow:(int)row inGroup:(int)group withProposedHeight:(float)proposedHeight;
{
	return 48.0f;
}
*/

#pragma mark Accessors
- (UIWindow *)mainWindow
{
    return _mainWindow;
}

- (void)setMainWindow:(UIWindow *)newMainWindow
{
    [_mainWindow release];
    _mainWindow = [newMainWindow retain];
}

@end
